local CommonOHOH = _G.CommonOHOH;
local M = CommonOHOH.class.new(script,script.Parent.base,script.Parent.Name);
local FunctionList = _G.ClientOHOH.load.FunctionList();
local Game_Cfg=_G.CommonOHOH.config.Game

function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);

    self.IsAuto=false
    self.player.AutoAttckEvent:Connect(function(isAuto)
        self.IsAuto=isAuto
		if isAuto then
            self:StartAuto()
		else
			self:StopAuto()
		end
	end)

    -- 退出游戏后，如果是自动战斗，继续去战斗
    self.player.BattleSateEvent:Connect(function(isBattle)
            if not isBattle and  self.IsAuto then
                self:AddProcess(function()
                    self:Wait(3.8)
                    if self.IsAuto then
                        self:StartAuto()
                    end
                end)
            end
    end)
end;


--进入一场战斗
function M.EnterBattle(self)
    
    if self.player:IsAutoAttack() then --如果是自动攻击状态开启自动攻击
        self:AutoAttack()
    end

    --开启攻击CD检测
    self:OpenAttackCdCheck()

    --开启攻击力检测
    self:OpenAttackDamgeCheck()

    --寻找目标检测
    self:OpenFindAttackTargetCheck()
end

--离开一场战斗
function M.OutBattle(self)
    --清除自动攻击
    self:ClearAutoAttack()
    --关闭攻击CD检测
    self:CloseAttackCdCheck()
    --关闭攻击力检测
    self:CloseAttackDamgeCheck()
    --关闭目标检测
    self:CloseFindAttackTargetCheck()
end



--客户端输入，退出战斗，待完成.....
function M.ExitBattle(self)

    if self.Battle then
        -- print("--------客户端发起退出---ExitBattle----->")
        local r=self.player:Invoke(FunctionList.ExitBattle)
        if  r then
            self.Battle:End(false)
       end
    end
end

--一场战斗胜利了
function M.Victory(self)
    if self.Battle then
        self.Battle:End(true)
    end
end


function M.StartAuto(self)

    if self:IsInBattle() then --在战斗中
        self:AutoAttack()
    else -- 不在战斗中，去战斗
        self:GoToBattle()
    end
end

function M.StopAuto(self)

    if  self.GoToBattleCtrl then
        self.GoToBattleCtrl:dtor()
        self.GoToBattleCtrl=nil
    end

    self:ClearAutoAttack()
end


-- 是否在战斗中
function M.IsInBattle(self)

    return self.parent:IsInBattle()
end





--去战斗
function M.GoToBattle(self)

    self.GoToBattleCtrl=self.player:AddComponent(require(script.GoToBattleCtrl)) --添加自动去战斗脚本

end

local gAutoAttackeCdScale=Game_Cfg.gAutoAttackeCdScale
-- 自动输入
function M.AutoAttack(self)
    if  self.autoConnect then
        return 
    end

    self.autoConnect= self:AddStepUpdate(function()
        self.player.TryAttackEvent:Action(gAutoAttackeCdScale)
    end)

end

-- 停止自动输入
function M.ClearAutoAttack(self)
    if self.autoConnect then
        self.autoConnect:Disconnect()
        self.autoConnect=nil
    end
end


function M.dtor(self)
	M.super.dtor(self);
end


_G.ClientOHOH.event_manager:RegistHandle(_G.ClientOHOH.event_list.battle_victory, function(player)
	player:GetComponent(_G.CommonOHOH.load.Common_AttackCtrl()):Victory()

end);



return M